#include "qrsagsbufferanalysis.h"
#include "ui_qrsagsbufferanalysis.h"
#include "qgsvectorlayer.h"
#include "qgsattributes.h"
#include <QCheckBox>
#include <QtMath>

QRSAGSBufferAnalysis::QRSAGSBufferAnalysis(QWidget *parent, QgsMapCanvas *mapCanvas) :
    QDialog(parent),
    ui(new Ui::QRSAGSBufferAnalysis)
{
    ui->setupUi(this);
    //获取当前列表中的图层

    this->mMapCanvas = mapCanvas;
    this->mActivateMapLayers = this->mMapCanvas->layers();
    ui->mInputComboBox->clear();
    QStringList mapLayerNameList;
    for(QgsMapLayer *mapLayer : this->mActivateMapLayers){
        mapLayerNameList.append(mapLayer->name());
    }
    ui->mInputComboBox->addItems(mapLayerNameList);

    //判断当前选择的图层中，是否有被选中的目标
    QgsMapLayer *currentMapLayer = this->mActivateMapLayers.at(ui->mInputComboBox->currentIndex());
    QgsMapLayerType type = currentMapLayer->type();
    if(type == QgsMapLayerType::VectorLayer){
        QgsVectorLayer *currentVectorMapLayer = (QgsVectorLayer *)currentMapLayer;
        if(currentVectorMapLayer->selectedFeatureCount()>0){
            ui->mSelectedFeaturesCheckBox->setEnabled(true);
        }
    }

    //当取消进度时，强行取消进度条
    connect(ui->mProcessCancelButton, SIGNAL(clicked(bool)), this, SLOT(cancelProcessing(bool)));
    connect(ui->mStartProcessingButton, SIGNAL(clicked(bool)), this, SLOT(bufferProcessing(bool)));
    connect(ui->mQuitButton, SIGNAL(clicked(bool)), this, SLOT(quitBufferAnalysis(bool)));
    connect(ui->mInputComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setSelectedFeaturesCheckBoxEnabled(int)));
}

QRSAGSBufferAnalysis::~QRSAGSBufferAnalysis()
{
    delete ui;
}

void QRSAGSBufferAnalysis::bufferProcessing(bool)
{
    QgsMapLayer *currentMapLayer = this->mActivateMapLayers.at(ui->mInputComboBox->currentIndex());
    QgsMapLayerType type = currentMapLayer->type();
    if(type != QgsMapLayerType::VectorLayer){
        return;
    }

    QgsVectorLayer *currentVectorMapLayer = (QgsVectorLayer *)currentMapLayer;
    QgsFeatureIds featureIds = currentVectorMapLayer->allFeatureIds();

    if(ui->mSelectedFeaturesCheckBox->isChecked()){
        featureIds = currentVectorMapLayer->selectedFeatureIds();
    }
    QgsFeatureIterator featureIterator = currentVectorMapLayer->getFeatures(featureIds);

    //获取当前被选中的图层
    bool dissolve = ui->mDissolveResultCheckBox->isChecked();
    double distance = ui->mDistanceFieldSpinBox->text().toDouble();
    distance = distance *360 / (2*M_PI*6371004);
    int segment = ui->mSegmentSpinBox->text().toInt();
    int endCapStyleIndex = ui->mEndCapStyleComboBox->currentIndex();
    int joinStyleIndex = ui->mJoinStylecomboBox->currentIndex();
    double miterLimit = ui->mMiterLimitSpinBox->text().toDouble();

    QgsGeometry::EndCapStyle capStyle = QgsGeometry::CapRound;
    if(endCapStyleIndex == 0){
        capStyle = QgsGeometry::CapRound;
    }else if(endCapStyleIndex == 1){
        capStyle = QgsGeometry::CapFlat;
    }else if(endCapStyleIndex == 2){
        capStyle = QgsGeometry::CapSquare;
    }
    QgsGeometry::JoinStyle joinStyle = QgsGeometry::JoinStyleRound;
    if(joinStyleIndex == 0){
        joinStyle = QgsGeometry::JoinStyleRound;
    }else if(joinStyleIndex == 1){
        joinStyle = QgsGeometry::JoinStyleMiter;
    }else if(joinStyleIndex == 2){
        joinStyle = QgsGeometry::JoinStyleBevel;
    }

    QgsFeatureList newFeatures;
    QgsFeature tempFeature;
    int current = 0;
    double total = 100.0/featureIds.size();
    if(dissolve){
        QVector<QgsGeometry> outGeometries;
        while (featureIterator.nextFeature(tempFeature)) {
            if(isCanceled){
                break;
            }

            QgsGeometry geometry = tempFeature.geometry();
            QgsGeometry outGeometry = geometry.buffer(distance, segment, capStyle, joinStyle, miterLimit);
            outGeometries.append(outGeometry);
            current += 1;
            ui->mProicessProgressBar->setValue(int(current*total));
        }

        QgsGeometry unionGeometry = QgsGeometry::unaryUnion(outGeometries);
        QgsFeature outFeature;
        outFeature.setGeometry(unionGeometry);
//        outFeature.setAttributes(tempFeature.attributes());
        outFeature.setAttributes(QgsAttributes() << QVariant(1) << QVariant("test1"));
        newFeatures.append(outFeature);
    }else {
        while (featureIterator.nextFeature(tempFeature)) {
            if(isCanceled){
                break;
            }

//            QgsAttributes attirbutes = tempFeature.attributes();
            QgsGeometry geometry = tempFeature.geometry();
            QgsFeature outFeature;
            QgsGeometry outGeometry = geometry.buffer(distance, segment, capStyle, joinStyle, miterLimit);
            QgsWkbTypes::GeometryType type = outGeometry.type();
            QgsWkbTypes::Type wkbtype = outGeometry.wkbType();
            outFeature.setGeometry(outGeometry);
//            outFeature.setAttributes(attirbutes);
            outFeature.setAttributes(QgsAttributes() << QVariant(1) << QVariant("test1"));
            newFeatures.append(outFeature);
            current += 1;
            ui->mProicessProgressBar->setValue(int(current*total));
        }
    }

    //完毕之后，创建新的图层，添加到图表中
    QString layerProperties = "Polygon?";    // 几何类型
        layerProperties.append(QString( "crs=EPSG:4326"));    // 参照坐标系
        layerProperties.append(QString( "&field=id:integer&field=name:string(50)" ));    // 添加字段
        layerProperties.append(QString( "&index=yes" ));        // 创建索引
        layerProperties.append(QString( "&memoryid=%1" ).arg( QUuid::createUuid().toString() ));

    QgsVectorLayer* newLayer = new QgsVectorLayer(layerProperties, "Scratch point layer",  "memory");
    newLayer->setCustomProperty("skipMemoryLayersCheck", 1);
    newLayer->startEditing();
    newLayer->addFeatures(newFeatures);
    newLayer->commitChanges();
    QgsProject::instance()->addMapLayer(newLayer);
    newLayer->updateExtents();
    this->mMapCanvas->refresh();
    ui->mProicessProgressBar->setValue(100);
}

void QRSAGSBufferAnalysis::cancelProcessing(bool)
{
    this->isCanceled = true;
    ui->mProicessProgressBar->setValue(0);
}

void QRSAGSBufferAnalysis::quitBufferAnalysis(bool)
{
    this->close();
}

void QRSAGSBufferAnalysis::setSelectedFeaturesCheckBoxEnabled(int)
{
    QgsMapLayer *currentMapLayer = this->mActivateMapLayers.at(ui->mInputComboBox->currentIndex());
    QgsMapLayerType type = currentMapLayer->type();
    if(type != QgsMapLayerType::VectorLayer){
        return;
    }

    QgsVectorLayer *currentVectorMapLayer = (QgsVectorLayer *)currentMapLayer;
    int selectedFeaturesCount = currentVectorMapLayer->selectedFeatureCount();
    ui->mSelectedFeaturesCheckBox->setEnabled(selectedFeaturesCount >= 1);
    ui->mSelectedFeaturesCheckBox->setChecked(false);
}
